<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\gaokao\Config;
use app\common\model\gaokao\Zhiyuan;
use app\common\validate\gaokao\Zhiyuan as ZhiyuanValidate;
use think\Cache;
use app\common\library\Sms;

class Gaokao extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    /**
     * 获取页面配置
     */
    public function config($type = 'zhiyuan'){
        $config = Config::cache('gaokao_config_'.$type)->where('type',$type)->order('id desc')->find();
        if($config){
            $config['content'] = richTextAbsoluteUrl($config['content']);
        }
        $config['users'] = $this->zhiyuan_users(true);
        $this->success("config", $config);
    }

    /**
     * 提交高考咨询
     */
    public function zhiyuan(){
        $data = $this->request->param('data/a');

        if(!isset($data['captcha'])){
            $this->error("请输入验证码");
        }

        $validate = new ZhiyuanValidate();

        if(!$validate->check($data)){
            $this->error($validate->getError());
        }

        if(!Sms::check($data['mobile'], $data['captcha'],'gaokaozx')){
            $this->error("验证码错误");
        }

        unset($data['captcha']);

        $hash = md5(json_encode($data));

        if(Cache::get($hash)){
            $this->error("已经提交过了");
        }

        $res = Zhiyuan::create($data);

        if($res){
            Cache::set($hash, 1, 3600);
            $this->success("提交成功");
        }

        $this->error("提交失败,请稍后重试");

    }

    /**
     * 志愿人数
     */
    public function zhiyuan_users($return = false){
        $list = Zhiyuan::limit(30)->order('id desc')->field('id,name,mobile,createtime')->select();

        foreach ($list as $key => &$item) {
            $item['name'] = remove_sens($item['name'],1,1);
            $item['mobile'] = remove_sens($item['mobile'],3,4);
        }

        $cof = [
           [ 'name' => '徐*中', 'mobile' => '185****9834','createtime' => 1594094371],
           [ 'name' => '张*华', 'mobile' => '176****7155','createtime' => 1594129831],
           [ 'name' => '刘*', 'mobile' => '166****8757','createtime' => 1594205971],
           [ 'name' => '黄*后', 'mobile' => '186****2377','createtime' => 1594043431],
           [ 'name' => '张*', 'mobile' => '137****1760','createtime' => 1594270771],
           [ 'name' => '翟*', 'mobile' => '187****2098','createtime' => 1594111831],
           [ 'name' => '许*冰', 'mobile' => '189****8773','createtime' => 1594025431],
           [ 'name' => '刘*洋', 'mobile' => '132****8744','createtime' => 1594018231],
           [ 'name' => '崔*', 'mobile' => '188****2058','createtime' => 1594205431],
           [ 'name' => '狄*', 'mobile' => '131****8797','createtime' => 1594216231],
        ];

        if(count($list) < 20){
            $list = array_merge($cof,$list);
        }

        if($return) return $list;
        $this->success('list', $list);
    }
}
